package com.security.service;

import com.security.mapper.RequestLogMapper;
import com.security.model.RequestLog;

import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class RequestLogService {

	private final RequestLogMapper requestLogMapper;

	@Async
	public void logRequest(RequestLog requestLog) {
		// 查找是否已有相同请求记录
		Optional<RequestLog> existingLog = requestLogMapper.findByMethodAndUrlAndQueryString(requestLog.getMethod(),
				requestLog.getUrl(), requestLog.getQueryString());

		if (existingLog.isPresent()) {
			// 更新已有记录
			RequestLog log = existingLog.get();
			log.setAccessTime(LocalDateTime.now());
			log.incrementAccessCount();
			requestLogMapper.insert(log);
		} else {
			// 保存新记录
			requestLogMapper.insert(requestLog);
		}
	}
}